<?php

/**
 * Auther: Joshua Conero
 * Date: 2017/5/11 0011 17:18
 * Email: brximl@163.com
 * Name: 项目系统基本公共函数
 */
namespace app\common;
use app\common\model\User;
use hyang\HRedis;
use hyang\Location;
use hyang\Net;
use hyang\SuPigeons;
use think\facade\Config;
use think\Db;
use think\facade\Session;

class Aurora
{
    /**
     * 获取系统反馈的统计值
     * @param $counter
     * @param bool $isGroup
     * @return array|mixed
     */
    public static function getFeekCount($counter,$isGroup=false){
        if($isGroup){
            $data = Db::table('sys_counter')->field('counter,count_start')->where('group_mk', $counter)->select();
            $retVal = [];
            foreach ($data as $v) {
                $key = $v['counter'];
                $retVal[$key] = $v['count_start'];
            }
            return $retVal;
        }else
            return Db::table('sys_counter')->where('counter', $counter)->value('count_start');
    }
//    public function session_cache(){
//        $ip = request()->ip();
//        $CacheFile = hash($ip.rand(100000,999999));
//    }

    /**
     * 访问 session 数据更新
     * @param $key
     * @param null $value
     * @return bool|string|array
     */
    public static function visitSession($key=null,$value=null){
        $skey = Config::get('setting.session_visit_key');
        $isUpdate = false;
        if(Session::has($skey)){
            $data = bsjson(Session::get($skey));
            if(empty($key)) return $data;
            if($value){
                $data[$key] = $value;
                $isUpdate = true;
            }
            elseif (is_array($key)){
                $data = array_merge($data,$key);
                $isUpdate = true;
            }
            elseif ($key){
                return isset($data[$key])? $data[$key]:'';
            }
            if($isUpdate) Session::set($skey,bsjson($data));
        }
        return $isUpdate;
    }
    /**
     * 获取地址信息
     * @return array|mixed
     */
    public static function location(){
        $ip = Net::getNetIp();
        Location::setIp($ip);
        $data = Location::getLocation();
        if(!is_array($data)) $data = [];
        return $data;
    }
    /**
     * 密码验证方式
     * @param $code string 明文
     * @param null $decode 密文， 为空时为加密否则为密码验证
     * @param null $salt 盐值， 用于crypt算法
     * @return boolean|string
     */
    public static function checkUserPassw($code,$decode=null,$salt=null){
        // crypt
        if(empty($salt)){
            $uid = getUserInfo('uid');
            if($uid){
                $user = new User();
                $salt = $user->where('uid',$uid)->value('salt');
            }
        }
        $salt = $salt? $salt:'__aurora__';
        if(empty($decode)){
            return crypt($code,$salt);
        }elseif ($decode){
            return $decode == crypt($code,crypt($code,$salt));
        }
        return false;
    }
    /**
     * @param null $userCode 用户代码
     * @return SuPigeons
     */
    public static function getPigeons($userCode=null){
        $option = config('pigeons.'.env('APP_ENV'));
        if($userCode){
            $option['user'] = $userCode;
        }
        return SuPigeons::getInstance($option);
    }
    /**
     * 公共用户登录处理
     * @param $uid
     * @param null|array $sessionKeepDt
     * @return null|string
     */
    public static function userLoginHandler($uid, $sessionKeepDt=null){
        $user = getUserInfo('user');
        if($user){
            return '';
        }
        $userModel = new User();
        $data = $userModel->field('uid,name,gender,account as user,dislogin_mk')
            ->where('uid',$uid)
            ->find()
            ->toArray();
        if('Y' == $data['dislogin_mk']){
            $msg = '您已经被禁止登陆系统，请联系网站人员！';
        }else {
            unset($data['dislogin_mk']);
            $sessionDt = $data;
            // 外部来需要保存到session中的值
            if($sessionKeepDt && is_array($sessionKeepDt)){
                $sessionDt = array_merge($sessionDt, $sessionKeepDt);
            }
            // token 检测
            if(!isset($sessionDt['token']) || empty($sessionDt['token'])){
                // su_pigeons 新增开关
                $suPigeons = Config::get('setting.su_pigeons');
                $suPigeonsAble = !empty($suPigeons) && ($suPigeons['able'] ?? false);
                if($suPigeonsAble){
                    try{
                        $pigeons = self::getPigeons($data['user']);
                        $token = $pigeons->getToken();
                        $sessionDt['token'] = $token;
                    }catch (\Exception $e){
                        debugOut(['系统获取 token 出错!', $e->getMessage()]);
                    }
                }
            }
            // 写入登记表
            $count = Db::table('sys_login')->where('uid', $data['uid'])->count();
            $count = ($count ? ($count) + 1 : 1);
            $sessionDt['loginId'] = md5($data['user']) . '___' . $count; // ___ 3 个下划线
            Session::set(Config::get('setting.session_user_key'), $sessionDt);
            $ip = Net::getNetIp();
            Db::table('sys_login')->insert([
                'uid' => $data['uid'],
                'ip' => $ip,
                'count' => $count
            ]);
            try{
                // 用于不同系统，同一服务器下统一语言的数据交互：如 aurora 和 center
                HRedis::serialize($sessionDt['loginId'], $data);
            }catch (\Exception $e){
                debugOut([
                    $e->getMessage(),
                    $e->getTraceAsString()
                ]);
            }
            $msg = null;
        }
        return $msg;
    }

    /**
     * 登录信息退出
     * @return bool
     */
    static function loginExit(){
        $success = false;
        $key = Config::get('setting.session_user_key');
        if(Session::has($key)){
            $success = true;
            Session::delete($key);
            try{
                // 删除Redis缓存数据
                HRedis::delete(getUserInfo('loginId'));
            }catch (\Exception $e){
                debugOut([
                    $e->getMessage(),
                    $e->getTraceAsString()
                ]);
            }
        }
        return $success;
    }
}